package com.jimmieran.myshop.myshopdatasyncservice.rabbitMQ;

import com.alibaba.fastjson.JSONObject;
import com.jimmieran.myshop.myshopdatasyncservice.service.EshopProductService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 数据同步服务-消费者Receiver 获取队列中的元数据解析数据进行下一步操作
 *
 * （1）然后通过spring cloud fegion调用eshop-product-service服务的各种接口， 获取数据
 * （2）将原子数据在redis中进行增删改
 * （3）将维度数据变化消息写入rabbitmq中另外一个queue，供数据聚合服务来消费
 */
@Component
@RabbitListener(queues = "myshop-data-change-queue")
public class MyshopDataSyncReceiver {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private EshopProductService eshopProductService;

    @Autowired
    private RabbitMQSender rabbitMQSender;

    //set聚合消息，去重处理
//    private Set<String> aggreSet = Collections.synchronizedSet(new HashSet());
    private Set<String> aggreSet = new ConcurrentSkipListSet<String>();

    public MyshopDataSyncReceiver() {
        new AggreQueueSendThread().start();
    }

    @RabbitHandler
    public void process(String message){
        JSONObject jsonObject = JSONObject.parseObject(message);
        String dataType = jsonObject.getString("data_type");

        if ("brand".equals(dataType)){
            processBrandDataChangeMessage(jsonObject);
        }else if("category".equals(dataType)) {
            processCategoryDataChangeMessage(jsonObject);
        } else if("product_intro".equals(dataType)) {
            processProductIntroDataChangeMessage(jsonObject);
        } else if("product_property".equals(dataType)) {
            processProductPropertyDataChangeMessage(jsonObject);
        } else if("product".equals(dataType)) {
            processProductDataChangeMessage(jsonObject);
        } else if("product_specification".equals(dataType)) {
            processProductSpecificationDataChangeMessage(jsonObject);
        }
    }

    /**
     * 处理 品牌维度的数据变更操作
     * @param jsonObject
     */
    public void processBrandDataChangeMessage(JSONObject jsonObject){
        String eventType = jsonObject.getString("event_type");
        Long id = jsonObject.getLong("id");

        if ("add".equals(eventType) || "update".equals(eventType)){
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findBrandById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("brand_" + dataJSONObject.getLong("id"), dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("brand_" + id);
        }
        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"brand\", \"id\": " + id + "}");
    }

    /**
     * 处理 分类维度的数据变更操作
     * @param messageJSONObject
     */
    private void processCategoryDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findCategoryById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("category_" + dataJSONObject.getLong("id"), dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("category_" + id);
        }
        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"category\", \"id\": " + id + "}");
    }

    /**
     * 处理 商品介绍维度的数据变更操作
     * @param messageJSONObject
     */
    private void processProductIntroDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductIntroById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("product_intro_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("product_intro_" + productId);
        }

        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"product\", \"id\": " + productId + "}");
    }

    /**
     * 处理 商品基本信息维度的数据变更操作
     * @param messageJSONObject
     */
    private void processProductDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("product_" + id, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("product_" + id);
        }

        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"product\", \"id\": " + id + "}");
    }


    /**
     * 处理 商品属性维度的数据变更操作
     * @param messageJSONObject
     */
    private void processProductPropertyDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductPropertyById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("product_property_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("product_property_" + productId);
        }

        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"product\", \"id\": " + productId + "}");
    }

    /**
     * 处理 商品规格维度的数据变更操作
     * @param messageJSONObject
     */
    private void processProductSpecificationDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductSpecificationById(id));
            Jedis jedis = jedisPool.getResource();
            jedis.set("product_specification_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            Jedis jedis = jedisPool.getResource();
            jedis.del("product_specification_" + productId);
        }

        //这里去重优化，缓解聚合服务和Redis的压力
        aggreSet.add("{\"dim_type\": \"product\", \"id\": " + productId + "}");
    }


    /**
     * 开辟一个线程间歇性不断轮询aggreSet中的message然后send
     */
    private class AggreQueueSendThread extends Thread{

        @Override
        public void run() {
            //轮询不断获取set中的信息并发送
            while (true){
                if (!aggreSet.isEmpty()){
                    for (String message : aggreSet){
                        rabbitMQSender.send("aggr-data-change-queue", message);
                    }
                    aggreSet.clear();
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
